package com.tsd.aspect;

import com.tsd.core.annotation.ClientSupplier;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.vo.HttpResult;
import com.tsd.system.service.SystemSettingService;
import com.tsd.system.vo.GlobalSetting;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName: CheckBindAspect
 * @Description: TODO
 * @Author: admin
 * @Date: 2022/11/14 11:30
 * @Version: 1.0
 */
@Order(1)
@Aspect
@Component
public class ClientSupplierAspect {

    @Resource
    private SystemSettingService systemSettingService;

    @Around(value = "@annotation(clientSupplier)")
    @SuppressWarnings("unchecked")
    public Object beforeCheckBind(ProceedingJoinPoint point, ClientSupplier clientSupplier) throws Throwable {
        if (clientSupplier.client() || clientSupplier.supplier()) {
            Object returnData = point.proceed();
            if (returnData == null) {
                return null;
            }
            if (returnData instanceof HttpResult) {
                HttpResult<Object> result = (HttpResult<Object>) returnData;
                if (result.getData() == null) {
                    return returnData;
                }
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                if (result.getData() instanceof List) {
                    List<Object> list = (List<Object>) result.getData();
                    if (clientSupplier.client()) {
                        ListUtil.forEach(list, data -> setting.procDisplay(data, GlobalSetting.TYPE_CLIENT));
                    }
                    if (clientSupplier.supplier()) {
                        ListUtil.forEach(list, data -> setting.procDisplay(data, GlobalSetting.TYPE_SUPPLIER));
                    }
                    result.setData(list);
                } else {
                    Object object = result.getData();
                    if (clientSupplier.client()) {
                        setting.procDisplay(object, GlobalSetting.TYPE_CLIENT);
                    }
                    if (clientSupplier.supplier()) {
                        setting.procDisplay(object, GlobalSetting.TYPE_SUPPLIER);
                    }
                    result.setData(object);
                }
                return result;
            }
            return returnData;
        } else {
            return point.proceed();
        }
    }
}
